
package com.be.beadmin.device.impl;

import com.alibaba.excel.util.StringUtils;
import com.be.beadmin.common.entity.PageEntity;
import com.be.beadmin.device.entity.EhsFile;
import com.be.beadmin.device.entity.EhsFile_;
import cn.hutool.core.util.ObjectUtil;
import com.be.beadmin.common.exception.BeadminException;
import com.be.beadmin.common.utils.JpaQueryBuilder;
import com.be.beadmin.common.utils.JpaSortBuilder;
import com.be.beadmin.device.entity.EhsItem;
import com.be.beadmin.device.repository.EhsItemRepository;
import com.be.beadmin.project.Util.MinioUtil;
import com.be.beadmin.project.config.MinioConfig;
import com.be.beadmin.project.entity.FileInfo;
import com.be.beadmin.project.entity.Info;
import com.be.beadmin.service.impl.MinioService;
import com.be.beadmin.service.service.SerialNumberService;
import io.minio.MinioClient;
import lombok.RequiredArgsConstructor;
import com.be.beadmin.device.mapper.EhsFileMapperEx;
import com.be.beadmin.device.repository.EhsFileRepository;
import com.be.beadmin.device.service.EhsFileService;
import com.be.beadmin.device.dto.input.EhsFileDto;
import com.be.beadmin.device.dto.output.EhsFileEx;
import com.be.beadmin.device.mapper.EhsFileMapper;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Order;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* @description 服务实现
* @author zty
* @date 2023-08-13
**/
@Service
@RequiredArgsConstructor
public class EhsFileServiceImpl implements EhsFileService {

    @Autowired
    private  EhsFileRepository ehsFileRepository;
    @Autowired
    private  EhsFileMapper ehsFileMapper;
    @Autowired
    private  EhsFileMapperEx ehsFileExMapper;
    @Autowired
    private SerialNumberService serialNumberService;
    @Autowired
    private EhsItemRepository ehsItemRepository;
    @Autowired
    private MinioService minioService;
    MinioUtil minioUtil = new MinioUtil();

    @Override
    public Page<EhsFileEx> getEhsFileByPage(PageEntity pageEntity) {
            Pageable pageable = PageRequest.of(
            pageEntity.getCurrent() -1,
            pageEntity.getPageSize());
            Page<EhsFile> page = ehsFileRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 =   JpaQueryBuilder.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(EhsFile_.delete), 0); //过滤为0
                    list.add(pre2);
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if(pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(EhsFile_.createTime).as(Date.class)));
                    }
                    return  criteriaBuilder.and(list.toArray(p));
                    }
                    , pageable);
            Page<EhsFileEx> page1 = page.map(ehsFileExMapper::toEntity);
            return page1;

    }

    @Override
    public void addEhsFile(EhsFileDto ehsFileDto) {
            EhsFile result = ehsFileRepository.findEhsFileByIdAndDelete(ehsFileDto.getId(), 0);
            if(ObjectUtil.isNotEmpty(result)) {
                throw new BeadminException("EhsFile不存在,请重新查询");
            }
            EhsFile ehsFile = ehsFileMapper.toEntity(ehsFileDto);
            ehsFile.setFileCode(serialNumberService.getNextSnByCode("FileCode"));
            ehsFileRepository.save(ehsFile);
    }

    @Override
    public void updateEhsFile(EhsFileDto ehsFileDto) {
            EhsFile ehsFile = ehsFileRepository.findEhsFileById(ehsFileDto.getId());
            ehsFile = ehsFileMapper.toEntity(ehsFileDto);
            ehsFileRepository.save(ehsFile);
    }

    @Override
    public String previewEhsFile(String id) throws Exception{
        EhsFile ehsFile=ehsFileRepository.findEhsFileById(id);
        return minioUtil.getPreviewFileUrl(ehsFile.getBucketName(),ehsFile.getNewFileName());
    }

    @Override
    public void downloadEhsFile(String id, HttpServletResponse response)throws Exception{
        EhsFile ehsFile=ehsFileRepository.findEhsFileById(id);
        MinioClient minioClient=MinioConfig.getMinioClient();
        InputStream inputStream   = null;
        OutputStream outputStream = null;
        if (StringUtils.isBlank(ehsFile.getNewFileName())) {
                response.setHeader("Content-type", "text/html;charset=UTF-8");
                String data = "文件下载失败";
                OutputStream ps = response.getOutputStream();
                ps.write(data.getBytes("UTF-8"));
                return ;
            }

        outputStream = response.getOutputStream();
        // 获取文件对象
        inputStream =minioClient.getObject(ehsFile.getBucketName(),ehsFile.getNewFileName());
        byte buf[] = new byte[1024];
        int length = 0;
        response.reset();
        String fileName = URLEncoder.encode(ehsFile.getNewFileName(), "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + fileName);
        response.setContentType("application/octet-stream");
            // 输出文件
            while ((length = inputStream.read(buf)) > 0) {
                outputStream.write(buf, 0, length);
            }
            System.out.println("下载成功");
            inputStream.close();
            outputStream.close();
            if (inputStream != null) {
                inputStream.close();
            }
    }

    @Override
    public void delEhsFile(String id) {
        EhsFile ehsFile = ehsFileRepository.findEhsFileById(id);
        ehsFile.setDelete(1);
        ehsFileRepository.save(ehsFile);
    }

    @Override
    public void delEhsFiles (List<String> ids) { }

    @Override
    public void uploadEhsFile(String ehsitemId, MultipartFile[] multipartFile, String fileName, String memo, String bucketName) throws Exception {
        EhsItem ehsItem = ehsItemRepository.findEhsItemById(ehsitemId);
        //对文件进行操作
        for(MultipartFile file:multipartFile) {
        EhsFile ehsFileDto = new EhsFile();

            //文件名
//            if (fileName == null || fileName.equals("")) {
//                fileName = multipartFile.getOriginalFilename();
//            }
            fileName=file.getOriginalFilename();
            ehsFileDto.setFileName(fileName);

            //判断同一个项目是否有相同的文件名
            int f = ehsFileRepository.countEhsFilesByFileNameAndItemNameAndDelete(fileName, ehsItem.getItemName(), 0);

            //文件后缀
            String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
            ehsFileDto.setFileExtEndDate(ext);

            String version;
            while (true) {
                version = "v1." + f;
                int num = ehsFileRepository.countEhsFilesByFileNameAndVersionAndDelete(fileName, version, 0);
                if (num == 0) {
                    break;
                } else {
                    f++;
                }
            }
            //System.out.println("version:"+version);
            ehsFileDto.setVersion(version);

            //文件大小
            BigDecimal fileSize = new BigDecimal(file.getSize());
            ehsFileDto.setFileSize(fileSize);
            //流水号
            //fileInfoDto.setSerialNo(serialNo);
            String fileCode = serialNumberService.getNextSnByCode("FileCode");
            ehsFileDto.setFileCode(fileCode);
            //项目id
            ehsFileDto.setEhsitemId(ehsitemId);
            //项目名称
            ehsFileDto.setItemName(ehsItem.getItemName());
            //检查单号
            ehsFileDto.setCheckId(ehsItem.getCheckId());
            //备注
            ehsFileDto.setMemo(memo);
            //设置bucketName
            ehsFileDto.setBucketName(bucketName);
            //System.out.println(fileInfoDto.toString());
            //处理文件

            String newFileName = fileName.substring(0, fileName.lastIndexOf(".")) + "-" + version + "." + ext;
//        //minioUtil.uploadFile(multipartFile,newFileName,bucketName);
//
//        minioService.uploadFile(bucketName,newFileName,multipartFile);
//        MinioClient minioClient = MinioConfig.getMinioClient();
////        String fileUrl = minioService.getObjectUrl(bucketName , newFileName);
//        String fileUrl = minioClient.presignedGetObject(bucketName , newFileName);
            String fileUrl = minioUtil.uploadFile3(file, bucketName, newFileName);
            ehsFileDto.setFileUrl(fileUrl);
            ehsFileDto.setNewFileName(newFileName);
            ehsFileRepository.save(ehsFileDto);
        }

    }

//    @Override
//    public byte[] previewFile(String filePath, String fileType) throws IOException {
//        File file = new File(filePath);
//
//        if ("pdf".equals(fileType)) {
//            return convertPdfToImage(file);
//        }
//
//        // Handle other file types (e.g., images) here if needed
//
//        return null;
//    }
//
//    private byte[] convertPdfToImage(File file) throws IOException {
//        PDDocument document = PDDocument.load(file);
//        PDFRenderer renderer = new PDFRenderer(document);
//
//        BufferedImage image = renderer.renderImageWithDPI(0, 300, ImageType.RGB);
//
//        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//        ImageIO.write(image, "png", byteArrayOutputStream);
//
//        document.close();
//        return byteArrayOutputStream.toByteArray();
//    }

}